/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.pbs.util;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.IOException;


public class PBSAuthenticator {

	private static final String PBS_IFF_CMD = "pbs_iff";
	private static final int PBS_CREDENTIALTYPE_NONE = 0;

	private static String authCommand = PBS_IFF_CMD;

	public static void setAuthCommand(String authCommand) {

		PBSAuthenticator.authCommand = authCommand;

	}

	public static void authenticate(String authSrvName, int authSrvPort, int clientPort) throws PBSException {

		Runtime runtime = Runtime.getRuntime();
		DataInputStream stdout = null;
		int authType = -1, ret = -1;

		try {
			String[] cmd = { authCommand,
					authSrvName, Integer.toString(authSrvPort),
					Integer.toString(clientPort) };
			Process proc = runtime.exec(cmd);
			stdout =  new DataInputStream(
					new BufferedInputStream(proc.getInputStream()));
			authType = stdout.readInt();
			ret = proc.waitFor();
		} catch (IOException e) {
			throw new PBSException(PBSErrorCode.BADCRED);
		} catch (InterruptedException e) {
			throw new PBSException(PBSErrorCode.BADCRED);
		} finally {
			if (stdout != null) {
				try {
					stdout.close();
				} catch (IOException e) {
					throw new PBSException(PBSErrorCode.BADCRED);
				}
			}
		}

		if (ret != 0) {
			throw new PBSException(PBSErrorCode.BADCRED);
		}
		if (authType != PBS_CREDENTIALTYPE_NONE) {
			throw new PBSException(PBSErrorCode.BADCRED);
		}

	}

}
